package com.hmkj.quote.queue;

import com.alibaba.fastjson.JSONObject;
import com.hmkj.boot.utils.SpringContextUtils;
import com.hmkj.core.constant.CacheID;
import com.hmkj.core.po.order.Order;
import com.hmkj.core.service.cache.RedisService;
import com.hmkj.core.service.order.OrderService;
import lombok.extern.slf4j.Slf4j;

/**
 * 操盘手处理跟单撤单队列线程
 *
 * @author eproo
 * @date 2017年03月16日 21:38
 */
@Slf4j
public class TraderCancelQueueThread implements Runnable {

    private RedisService redisService = SpringContextUtils.getBean(RedisService.class);
    private OrderService orderService = SpringContextUtils.getBean(OrderService.class);

    @Override
    public void run() {
        while (true) {
            try {
                if (startQueue()) {
                    Thread.sleep(1000);
                }
            } catch (Exception e) {
                log.error(e.getMessage());
                e.printStackTrace();
            }
        }
    }

    private boolean startQueue() throws Exception {
        boolean isFinish = false;
        try {
            JSONObject obj = redisService.pop(CacheID.QUEUE_FOLLOW_CANCEL,JSONObject.class);
            if (null == obj || null == obj.getInteger("orderId")) {
                return true;
            }
            Order order = orderService.selectByPrimaryKey(obj.getInteger("orderId"));
            log.info("处理订单撤单，订单Id："+obj.getInteger("orderId"));
            orderService.cancelOrder(order.getId(),order.getUserId(),Order.CANCLETYPE.T4);
        } catch (Exception e) {
            log.error("执行订单撤单队列失败：" + e.getMessage());
            e.printStackTrace();
        }
        return isFinish;
    }
}
